import React from "react";
import {Form, Input, InputNumber, Popconfirm, Table} from "antd";
import styles from "components/searchTable/SearchHeader.less";
import {getTableProps} from "components/searchTable/SearchTable";
import SearchHeader from "components/searchTable/SearchHeader";
import {getFormConfig} from "@/pages/flowmonitor/components/variablelist/RunningVariable/tableConfig";

const EditableContext = React.createContext();
// let editingKey ='';
// let editDatas = [];

class EditableCell extends React.Component {
  getInput = () => {
    // eslint-disable-next-line react/destructuring-assignment
    if (this.props.inputType === 'number') {
      return <InputNumber />;
    }
    return <Input />;
  };

  renderCell = ({getFieldDecorator}) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{margin: 0}}>
            {getFieldDecorator(dataIndex, {
              rules: [
                {
                  required: true,
                  message: `Please Input ${title}!`,
                },
              ],
              initialValue: record.type === 'serializable' ? JSON.stringify(record[dataIndex]) : record[dataIndex],
            })(this.getInput())}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}

class EditTable extends React.Component {

  state = {
    editingKey :'',
    editDatas : [],
  }

  constructor(props) {
    super(props);

    this.columns = [
      {
        title: "序号",
        dataIndex: "id",
        render: (value, record, index) => {
          const {page: {pageNum, pageSize}} = this.props;
          return (pageNum - 1) * pageSize + index + 1;
        },
      },
      {title: "流程实例ID", dataIndex: "processInstanceId"},
      {title: "任务ID", dataIndex: "taskId"},
      {title: "变量名称", dataIndex: "name"},
      {title: "变量类型", dataIndex: "type"},
      {
        title: "变量值",
        dataIndex: "value",
        editable: true,
        render: (value, record) => {
          if(record.type === 'serializable'){
            return JSON.stringify(value);
          }else {
            return value;
          }

        },
      },
      {
        title: '操作',
        dataIndex: 'operation',
        render: (text, record) => {
          const editable = this.isEditing(record);
          return editable ? (
            <span>
              <EditableContext.Consumer>
                {form => (
                  <a
                    onClick={() => this.save(form, record)}
                    style={{marginRight: 8}}
                  >
                    保存
                  </a>
                )}
              </EditableContext.Consumer>
              <Popconfirm title="确定取消?" onConfirm={this.cancel}>
                <a>取消</a>
              </Popconfirm>
            </span>
            )
            : (
              // eslint-disable-next-line react/destructuring-assignment
              <a disabled={this.state.editingKey !== ''} onClick={() => this.edit(record.id)}>
                编辑
              </a>
            );
        },
      },
    ];
  }

  // eslint-disable-next-line react/destructuring-assignment
  isEditing = record => record.id === this.state.editingKey;

  cancel = () => {
    this.setState({editingKey:''})
  };

  save= (form, record) => {
    const { dispatch, page } = this.props;
    
    form.validateFields((error, row) => {
      dispatch({ type: 'FlowMonitor/updateVariable', payload: {...record, value:row.value} }).then(()=>{
        this.setState({editingKey:''})
        // eslint-disable-next-line no-unused-expressions,react/destructuring-assignment
        this.props.handlePageChange(page.pageNum, page.pageSize);
      });
    })

/*    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      // eslint-disable-next-line react/destructuring-assignment
      const newData = this.state.editDatas;
      const index = newData.findIndex(item => record.id === item.id);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        this.setState({editDatas:newData, editingKey:''})
      } else {
        newData.push(row);
        this.setState({editDatas:newData, editingKey:''})
      }
    }); */
  }

  edit = (key) => {
    // this.saveDatas();
    this.setState({editingKey: key})
  }

  saveDatas = () => {
    const { runningVariableList } = this.props;
    const { datas = []} = runningVariableList;
    this.setState({editDatas: datas})
  }


  render() {
    const components = {
      body: {
        cell: EditableCell,
      },
    };
    const { runningVariableList, page } = this.props;
    const { datas = [], totalCount} = runningVariableList;
    const { pageNum, pageSize} = page;
    let data = [];
    // eslint-disable-next-line react/destructuring-assignment
    if (this.state.editDatas.length > 0){
      // eslint-disable-next-line react/destructuring-assignment
      data = this.state.editDatas;
    }else {
      data = datas;
 /*     data.map(record => {
        if(record.type === 'serializable'){
          record.value = JSON.stringify(record.value);
        }
        return record;
      }); */
    }

    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex === 'age' ? 'number' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });

    return (
      // eslint-disable-next-line react/destructuring-assignment
      <EditableContext.Provider value={this.props.form}>
        <SearchHeader
          formConfig={getFormConfig()}
          wrappedComponentRef={this.refSearch}
          /* eslint-disable-next-line react/destructuring-assignment */
          onSearch={this.props.handleSearch}
        />
        <div
          ref={this.tableRef}
          className={styles.table}
        >
          <Table
            {...getTableProps({
              rowKey:"id",
              components,
              dataSource:data,
              columns,
              rowClassName:"editable-row",
              pagination:{
                current: pageNum,
                pageSize,
                total: totalCount,
                // eslint-disable-next-line react/destructuring-assignment
                onChange: this.props.handlePageChange,
                // eslint-disable-next-line react/destructuring-assignment
                onShowSizeChange: this.props.handlePageChange,
              },
            })
          }
          />
        </div>
      </EditableContext.Provider>
    );
  }
}

const EditableTable = Form.create()(EditTable);
export default EditableTable;

